<template>
  <div class="register-container">
    <el-form ref="registrationForm" :model="registrationForm" :rules="registrationRules" class="login-form" autocomplete="on" label-position="left">

      <div class="title-container">
        <h3 class="title">
          用户注册
        </h3>
        <lang-select class="set-language" />
      </div>

      <el-form-item prop="userName">
        <span class="svg-container">
          <svg-icon icon-class="user" />
        </span>
        <el-input
          ref="userName"
          v-model="registrationForm.userName"
          :placeholder="$t('用户名')"
          name="userName"
          type="text"
          tabindex="1"
          autocomplete="on"
        />
      </el-form-item>
      
      <el-form-item prop="userSex">
        <span class="svg-container">
          <svg-icon icon-class="userSex" />
        </span>
        <el-select v-model="registrationForm.userSex" :placeholder="$t('性别')">
          <el-option label="男" value="男"></el-option>
          <el-option label="女" value="女"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="userAge">
        <span class="svg-container">
          <svg-icon icon-class="age" />
        </span>
        <el-input
          ref="userAge"
          v-model="registrationForm.userAge"
          :placeholder="$t('年龄')"
          name="userAge"
          type="number"
          tabindex="2"
          autocomplete="on"
        />
      </el-form-item>
      <el-form-item prop="idCardNumber">
        <span class="svg-container">
          <svg-icon icon-class="id-card" />
        </span>
        <el-input
          ref="idCardNumber"
          v-model="registrationForm.idCardNumber"
          :placeholder="$t('身份证号码')"
          name="idCardNumber"
          type="text"
          tabindex="3"
          autocomplete="on"
        />
      </el-form-item>
      <el-form-item prop="userPhone">
        <span class="svg-container">
          <svg-icon icon-class="contact" />
        </span>
        <el-input
          ref="userPhone"
          v-model="registrationForm.userPhone"
          :placeholder="$t('联系方式')"
          name="userPhone"
          type="text"
          tabindex="6"
          autocomplete="on"
        />
      </el-form-item>
      <el-tooltip v-model="capsTooltip" content="Caps lock is On" placement="right" manual>
        <el-form-item prop="password">
          <span class="svg-container">
            <svg-icon icon-class="password" />
          </span>
          <el-input
            :key="passwordType"
            ref="password"
            v-model="registrationForm.password"
            :type="passwordType"
            :placeholder="$t('密码')"
            name="password"
            tabindex="4"
            autocomplete="on"
            @keyup.native="checkCapslock"
            @blur="capsTooltip = false"
          />
          <span class="show-pwd" @click="showPwd">
            <svg-icon :icon-class="passwordType === 'password'? 'eye' : 'eye-open'" />
          </span>
        </el-form-item>
      </el-tooltip>
      <el-form-item prop="confirmPassword">
        <span class="svg-container">
          <svg-icon icon-class="confirm-password" />
        </span>
        <el-input
          ref="confirmPassword"
          v-model="registrationForm.confirmPassword"
          :placeholder="$t('确认密码')"
          name="confirmPassword"
          type="password"
          tabindex="5"
          autocomplete="on"
        />
      </el-form-item>
      <el-button :loading="loading" type="primary" style="width:100%;margin-bottom:30px;" @click="handleRegistration">注册</el-button>



      <div style="position:relative">
          <a href="/login">
            <em class="bold">已有账号？去登录</em>
          </a>
      </div>
    </el-form>
  <!--
      <el-dialog :title="$t('login.thirdparty')" :visible.sync="showDialog">
        {{ $t('login.thirdpartyTips') }}
        <br>
        <br>
        <br>
        <social-sign /> 其他登录方式
      </el-dialog> -->
  </div>
</template>

<script>

import LangSelect from '@/components/LangSelect';
import { tfExistUserName, registerUser } from '@/api/user';
export default {
  name: 'RegistrationPage',
  components: { LangSelect },
  data() {
    return {
      registrationForm: {
        userName: '',
        userSex: '',
        userAge: '',
        idCardNumber: '',
        userPhone: '',
        password: '',
        confirmPassword: ''
      },
      registrationRules: {
        userName: [{ required: true, trigger: 'blur', validator: this.validateUsername }],
        userSex: [{ required: true, trigger: 'change' }],
        userAge: [{ required: true, trigger: 'blur', validator: this.validateAge }],
        idCardNumber: [{ required: true, trigger: 'blur', validator: this.validateIdNumber }],
        userPhone: [{ required: true, trigger: 'blur', validator: this.validatePhone }],
        password: [{ required: true, trigger: 'blur', validator: this.validatePassword }],
        confirmPassword: [{ required: true, trigger: 'blur', validator: this.validateConfirmPassword }],
      },
      passwordType: 'password',
      capsTooltip: false,
      loading: false
    };
  },
  methods: {
    validateUsername(rule, value, callback) {
      if (value === '') {
        callback(new Error('用户名不能为空'));
        return;
      }
      tfExistUserName(this.registrationForm.userName).then(response => {
        if (response.data.valid) {
          callback();
        } else {
          callback(new Error('用户名已存在，请重新输入'));
        }
      }).catch(() => {
        callback(new Error('验证用户名时出现错误，请稍后再试'));
      });
    },
    validateAge(rule, value, callback) {
      if (!value || value < 0 || value > 120) {
        callback(new Error('请输入合法的年龄'));
      } else {
        callback();
      }
    },
    validateIdNumber(rule, value, callback) {
      // 身份证号码简单验证，这里只是一个示例，实际应用中可使用更复杂的验证逻辑
      const idNumberRegex = /^\d{17}(\d|X|x)$/;
      if (!value ||!idNumberRegex.test(value)) {
        callback(new Error('请输入合法的身份证号码'));
      } else {
        callback();
      }
    },
    validatePassword(rule, value, callback) {
      if (value.length < 6 || value.length > 15) {
        callback(new Error('密码长度应大于6，小于15'));
      } else {
        callback();
      }
    },
    validateConfirmPassword(rule, value, callback) {
      if (value!== this.registrationForm.password) {
        callback(new Error('两次输入的密码不一致'));
      } else {
        callback();
      }
    },
    validatePhone(rule, value, callback) {
      const phoneRegex = /^1[3-9]\d{9}$/;
      if (!value ||!phoneRegex.test(value)) {
        callback(new Error('请输入正确的手机号码'));
      } else {
        callback();
      }
    },
    checkCapslock(e) {
      const { key } = e;
      this.capsTooltip = key && key.length === 1 && (key >= 'A' && key <= 'Z');
    },
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = '';
      } else {
        this.passwordType = 'password';
      }
      this.$nextTick(() => {
        this.$refs.password.focus();
      });
    },
    handleRegistration() {
      this.$refs.registrationForm.validate(valid => {
        if (valid) {
          this.loading = true;
          // 调用后端注册 API，
          console.log("注册:" + this.registrationForm);
          registerUser(this.registrationForm).then(response => {
            this.loading = false;
            if (response.msg === "操作成功") {
              this.$message.success('注册成功！');
              // 这里可以添加注册成功后的逻辑，比如跳转到登录页面等
              this.$router.push('/login');
            } else {
              this.$message.error('注册失败：');
            }
          }).catch(() => {
            this.loading = false;
            console.log('注册失败，请稍后再试');
          });
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    }
  }
};
</script>

<style lang="scss">
/* 修复input 背景不协调 和光标变色 */
/* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */

$bg: #283443;
$light_gray: #fff;
$cursor: #fff;

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
.register-container.el-input input {
    color: $cursor;
  }
}

/* reset element-ui css */
.register-container {
.el-input {
    display: inline-block;
    height: 47px;
    width: 85%;

    input {
      background: transparent;
      border: 0px;
      -webkit-appearance: none;
      border-radius: 0px;
      padding: 12px 5px 12px 15px;
      color: $light_gray;
      height: 47px;
      caret-color: $cursor;

      &:-webkit-autofill {
        box-shadow: 0 0 0px 1000px $bg inset!important;
        -webkit-text-fill-color: $cursor!important;
      }
    }
  }

.el-form-item {
    border: 1px solid rgba(255, 255, 255, 0.1);
    background: rgba(0, 0, 0, 0.1);
    border-radius: 5px;
    color: #454545;
  }
}
</style>

<style lang="scss" scoped>
$bg: #2d3a4b;
$dark_gray: #889aa4;
$light_gray: #eee;

.register-container {
  min-height: 100%;
  width: 100%;
  background-color: $bg;
  overflow: hidden;

.login-form {
    position: relative;
    width: 520px;
    max-width: 100%;
    padding: 160px 35px 0;
    margin: 0 auto;
    overflow: hidden;
  }

.tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;

    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }

.svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }

.title-container {
    position: relative;

  .title {
      font-size: 26px;
      color: $light_gray;
      margin: 0px auto 40px auto;
      text-align: center;
      font-weight: bold;
    }

  .set-language {
      color: #fff;
      position: absolute;
      top: 3px;
      font-size: 18px;
      right: 0px;
      cursor: pointer;
    }
  }

.show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }

.thirdparty-button {
    position: absolute;
    right: 0;
    bottom: 6px;
  }

  @media only screen and (max-width: 470px) {
  .thirdparty-button {
      display: none;
    }
  }
}
</style>